package com.zhong.beautifulimageapp.fragments;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.zhong.beautifulimageapp.R;
import com.zhong.beautifulimageapp.adapter.RecyclerViewAdapter;
import com.zhong.beautifulimageapp.model.CommonVariable;
import com.zhong.beautifulimageapp.model.EventBusMessageAboutUserName;
import com.zhong.beautifulimageapp.model.TopicBriefItem;
import com.zhong.beautifulimageapp.model.TopicBriefList;
import com.zhong.beautifulimageapp.network.GetContentFromNetwork;
import com.zhong.beautifulimageapp.utils.BaseFragments;
import com.zhong.beautifulimageapp.utils.OnRcvScrollListener;


import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class AllTopicFragment extends BaseFragments implements SwipeRefreshLayout.OnRefreshListener {


    @BindView(R.id.all_recycle)
    RecyclerView mAllRecycle;
    @BindView(R.id.all_swipe)
    SwipeRefreshLayout mAllSwipe;
    private List<TopicBriefItem> mItems = new ArrayList<>();
    private GetContentFromNetwork mNetwork;
    private RecyclerViewAdapter mAdapter;

    public AllTopicFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public String getFragmentTitle() {
        return "全部";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_all_topic, container, false);
        ButterKnife.bind(this, view);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(CommonVariable.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        mNetwork = retrofit.create(GetContentFromNetwork.class);
        int widthDp = CommonVariable.getScreenWidthDp(getContext());
        /**
         * 机型适配
         */
        if (widthDp >= 1200){
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3);
            mAllRecycle.setLayoutManager(gridLayoutManager);
        }else if (widthDp >= 800){
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 2);
            mAllRecycle.setLayoutManager(gridLayoutManager);
        }else {
            LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
            mAllRecycle.setLayoutManager(layoutManager);
        }
        mAdapter = new RecyclerViewAdapter(mItems, getContext(), 0);
        mAllRecycle.setAdapter(mAdapter);
        mAllSwipe.setOnRefreshListener(this);
        mAllRecycle.setOnScrollListener(new OnRcvScrollListener(){
            @Override
            public void onBottom() {
                addPage();
                getMoreAllTopic(getPage(), getLimit(), getMyTab(), getMdrender(), 0);
            }
        });
        setTab("all");
        getMoreAllTopic(getPage(), getLimit(), getMyTab(), getMdrender(), 0);
        return view;
    }

    private void getMoreAllTopic(int page, int limit, String tag, String mdrender, final int flag) {
        mNetwork.getTopicListContent(tag, String.valueOf(page), String.valueOf(limit), mdrender)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TopicBriefList>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(TopicBriefList list) {
                        if (flag == 0){
                            mItems.addAll(list.getData());
                        }else {
                            mItems.clear();
                            mItems.addAll(list.getData());
                        }
                        mAdapter.notifyDataSetChanged();
                        if (mAllSwipe.isRefreshing()) {
                            mAllSwipe.setRefreshing(false);
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        Toast.makeText(getContext(), "网络不给力", Toast.LENGTH_SHORT).show();
                        if (mAllSwipe.isRefreshing()) {
                            mAllSwipe.setRefreshing(false);
                        }
                        t.printStackTrace();
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void onRefresh() {
        restorePage();
        getMoreAllTopic(getPage(), getLimit(), getMyTab(), getMdrender(), 1);
    }

    /**
     * 用于主页中5个分类所展示话题头像的点击进入作者个人详情界面中
     * @param loginName 传递的用户登录名
     */
    @Subscribe
    public void goToMy(EventBusMessageAboutUserName loginName){
        goToMyInfo(loginName.getLoginName());
    }

    /**
     * 用于点击话题后进入话题详情界面
     * @param id 话题的id
     */
    @Subscribe
    public void getTopicId(String id){
        goToTopicDetail(id);
    }
}
